#include "sys_config.h"

static int socket_fd = -1;
static char recv_buf[256] = "";

//存储对端IP地址和端口号信息专用地址结构体
struct sockaddr_in gloabel_client_addr;

/**
 * @brief 初始化UDP服务器
 * @note 端口号SERVER_PORT定义在"sys_config.h"
 * @param {*}
 * @return {*}
 */
int UdpServer_Init(void)
{
    int result_code = 0; // 函数的返回值

    socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(socket_fd < 0){
        printf("UdpServer_Init: socket create failed\n");
        return -1;
    }

    struct sockaddr_in local;
    local.sin_family = AF_INET;                           // IPV4
    local.sin_port = htons(SERVER_PORT);                     // 端口号
    local.sin_addr.s_addr = inet_addr(g_IP_Addr); // 使用本地IP地址进行创建UDP服务端

    printf("LocalIP = %s\n", g_IP_Addr);
    result_code = bind(socket_fd, (const struct sockaddr *)&local, sizeof(local));
    if(result_code < 0){
        printf("TcpServer_Init: bind failed\n");
        return -1;
    }
    oled_show("wait clinet...", OLED_BUF_LEN, 1);
#if 1
    while(1){
        //读取NFC???
        char recvbuf[10] = {0};
        char sendbuf[10] = "ok";

        gloabel_client_addr.sin_family = AF_INET;                           // IPV4
        gloabel_client_addr.sin_port = htons(SERVER_PORT);                     // 接收端端口号
        socklen_t len = sizeof(gloabel_client_addr);

        //发送ok
        int ret = -1;
        sendto(socket_fd,sendbuf,strlen(sendbuf),0,(const struct sockaddr*)&gloabel_client_addr,len);
        sleep(5);

        struct sockaddr_in client;
        memset(&client,0,sizeof(client));
        //非阻塞接收数据
        ret = recvfrom(socket_fd, recvbuf, sizeof(recvbuf), MSG_DONTWAIT,(struct sockaddr*)&client,&len);
        if(ret > 0){
            //ip和nfc内ip对比
            if(client.sin_addr.s_addr == gloabel_client_addr.sin_addr.s_addr){
                //再次发送ok，进入后续流程
                sendto(socket_fd,sendbuf,strlen(sendbuf),0,(const struct sockaddr*)&gloabel_client_addr,len);  
                oled_show("success clinet.", OLED_BUF_LEN, 1);
                break;
            }
        }else{
            //更新IP地址？？？？？
            continue;
        }
    }
#endif
    return 0;
}


/**
 * @brief 接收请求、数据任务
 * @note 处理连接请求，接收数据，进行JSON解析后，存入全局变量globals_cmd_now; 发送对应指令给单片机
 * @param {*}
 * @return {*}
 */
void Udp_Recv_Tack(void)
{
    int ret = 0;
    while(1){
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int ret = 0;
        memset(recv_buf, 0, sizeof(recv_buf));
        
        ret = recvfrom(socket_fd, recv_buf, sizeof(recv_buf), 0,(struct sockaddr*)&client,&len);
        if(ret <= 0){
            printf("Udp_Recv_Tack: disconnect client\n");
        }
        printf("Udp_Recv_Tack: recv_buf = %s\n", recv_buf);

        ret = 0;
        osMutexAcquire(globals_Mutex_ID, osWaitForever);
        ret = Json_Ana_RecvFromNet(recv_buf);
        switch (ret)
        {
        case 0:
            globals_cmd_now.flag_cmd_update = 1;
            globals_cmd_now.response = RESPONSE_SUCCESS;
            break;
        case 1:
            globals_cmd_now.response = RESPONSE_ANA_FAILED;
            break;
        case 2:
            globals_cmd_now.response = RESPONSE_UNDEFINE;
            break;
        default:
            break;
        }
        osMutexRelease(globals_Mutex_ID);
    }
}


void Udp_Send_To_Client(void)
{
    //获取对端IP地址和端口号，实现发送过程！！！！！！！！！！
    
    int ret = -1;
    //获取封装的json数据包
    char * json_data = Json_Enc_SendToNet();
    ret = sendto(socket_fd,json_data,strlen(json_data),0,(const struct sockaddr*)&gloabel_client_addr,sizeof(gloabel_client_addr));
    if(ret <= 0){
        printf("Tcp_Send_Tack send data error\n");
    }
    free(json_data);
    json_data = NULL;

}
